package net.entelijan.cobean.text.validator;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;

import net.entelijan.cobean.text.IValidationResult;
import net.entelijan.cobean.text.IValidator;

public class DateRangeValidator<T extends Date> implements IValidator<T> {

	private Date min;

	private Date max;

	private SimpleDateFormat sdf = new SimpleDateFormat();

	public DateRangeValidator() {
		super();
	}

	public DateRangeValidator(String datePattern) {
		super();
		sdf = new SimpleDateFormat(datePattern);
	}

	public DateRangeValidator(Date min, Date max) {
		super();
		this.min = min;
		this.max = max;
	}

	public DateRangeValidator(Date min, Date max, String datePattern) {
		super();
		sdf = new SimpleDateFormat(datePattern);
		this.min = min;
		this.max = max;
	}

	public DateRangeValidator(String min, String max, String datePattern) {
		super();
		sdf = new SimpleDateFormat(datePattern);
		try {
			this.min = sdf.parse(min);
		} catch (ParseException e) {
			throw new IllegalArgumentException("'" + min
					+ "' is not a valid date. Use '" + datePattern + "'");
		}
		try {
			this.max = sdf.parse(max);
		} catch (ParseException e) {
			throw new IllegalArgumentException("'" + max
					+ "' is not a valid date. Use '" + datePattern + "'");
		}
	}

	@Override
	public IValidationResult validate(final Date value) {
		if (value == null || value.before(min) || value.after(max)) {
			return new IValidationResult() {

				@Override
				public String getMessage() {
					return (value == null ? "''" : sdf.format(value))
							+ " is not between " + sdf.format(min) + " and "
							+ sdf.format(max);
				}

				@Override
				public boolean ok() {
					return false;
				}

			};

		} else {
			return new IValidationResult() {

				@Override
				public String getMessage() {
					return null;
				}

				@Override
				public boolean ok() {
					return true;
				}

			};
		}
	}

	public Date getMin() {
		return min;
	}

	public void setMin(Date min) {
		this.min = min;
	}

	public Date getMax() {
		return max;
	}

	public void setMax(Date max) {
		this.max = max;
	}

}
